package com.briup.cloud.framework.resource.web.interceptor;

import com.briup.cloud.framework.resource.web.rest.RemoteService;
import com.briup.framework.utils.sercurity.SecurityUtils;
import com.briup.framework.utils.web.Response;
import com.briup.framework.utils.web.SecurityUserDetails;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.oauth2.provider.OAuth2Authentication;
import org.springframework.stereotype.Component;
import org.springframework.util.ObjectUtils;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @Author guomiao
 * @Date 2022/4/8 17:14
 */
@Component
public class CurrentUserInterceptor implements HandlerInterceptor {
    @Lazy
    @Autowired
    private RemoteService remoteService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        Authentication auth = SecurityContextHolder.getContext().getAuthentication();
        if(auth instanceof OAuth2Authentication){
            OAuth2Authentication o2Auth = (OAuth2Authentication) auth;
            if(!ObjectUtils.isEmpty(o2Auth.getUserAuthentication())){
               Response<SecurityUserDetails> resp =  remoteService.hello();
                SecurityUtils.setUsers(resp.getData());
            }
        }
        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        SecurityUtils.clear();
    }
}
